/**
 * Created by FeLiX on 2016/9/9.
 */


const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();
const templating = require('./middleware/templating');
const addControllers = require('./middleware/controllers');
const config = require('./config');

const app = new Koa();

//isProduction 它判断当前环境是否是production环境。如果是，就使用缓存，如果不是，就关闭缓存。
const isProduction = process.env.NODE_ENV === 'production';

//URL 请求日志
app.use(async(ctx, next)=> {
  console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
  var
    start = new Date().getTime(),
    execTime;
  await next();
  execTime = new Date().getTime() - start;
  ctx.response.set('X-Response-Time', `${execTime}ms`);
});

//支持静态文件
if (!isProduction) {
  var staticFiles = require('./middleware/static-files');
  app.use(staticFiles(config.staticName, config.staticDir));
}

//解析请求body
app.use(bodyParser());

//支持 nunjucks 视图模板
app.use(templating(config.viewsDir, {
  noCache: !isProduction,
  watch: !isProduction
}));

//加载控制器
addControllers(router);

//支持路由中间件
app.use(router.routes());

app.listen(config.port);
console.log(`app started at port ${config.port}`);
